<?php

declare(strict_types=1);

namespace NanQi\Hope\Aspect;

use Hyperf\Cache\AnnotationManager;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use NanQi\Hope\Annotation\MultiTransactional;
use NanQi\Hope\Base\BaseAspect;

/**
 * @Aspect
 */
class MultiTransactionAspect extends BaseAspect
{
    public $annotations = [
        MultiTransactional::class,
    ];

    /**
     * @var AnnotationManager
     */
    protected $annotationManager;

    public function __construct(AnnotationManager $annotationManager)
    {
        $this->annotationManager = $annotationManager;
    }

    /**
     * @param ProceedingJoinPoint $proceedingJoinPoint
     * @return mixed
     * @throws \Throwable
     */
    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        $annotation = $this->getAnnotation($proceedingJoinPoint, MultiTransactional::class);
        return Db::connection($annotation->pool)->transaction(
            function () use ($proceedingJoinPoint) {
                return $proceedingJoinPoint->process();
            }
        );
    }
}
